package com.gushenge.core

import android.app.Application
import com.tencent.mmkv.MMKV
import kotlin.reflect.KProperty


/**
 *
 * @Author:         yu
 * @CreateDate:     2021/3/25 14:57
 */
class MMKVUtils<T>(var name: String, var default: T) {

    companion object{
        lateinit var context: Application
        lateinit var spName: String
        fun init(context: Application, spName: String){
            Companion.context = context
            Companion.spName = spName
        }
    }
    //重载下
    operator fun getValue(thisRef: Any?, property: KProperty<*>)=get(name,default) as T

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = put(name, value)

    val mmkv: MMKV by lazy { MMKV.defaultMMKV() }
     fun get(name: String, value: T)= when (value) {
         is Int -> mmkv.decodeInt(name, value)
         is Float -> mmkv.decodeFloat(name, value)
         is Long -> mmkv.decodeLong(name, value)
         is Boolean -> mmkv.decodeBool(name, value)
         is String -> mmkv.decodeString(name, value)
             else -> throw IllegalArgumentException("mmkv can't be get this type")

     }
    fun put(name: String, value: T){
        when(value) {
            is Int -> mmkv.encode(name, value)
            is Float -> mmkv.encode(name, value)
            is Long -> mmkv.encode(name, value)
            is Boolean -> mmkv.encode(name, value)
            is String -> mmkv.encode(name, value)
            else -> throw IllegalArgumentException("mmkv can't be save this type")
        }
    }
}